const path = require("path");

const Koa = require("koa");
const { koaBody } = require("koa-body");
const KoaStatic = require("koa-static");

const { APP_PORT } = require("./config/config.default");
const errHandler = require("./app/errHandler");
const router = require("./routes/index");
const app = new Koa();

// 跨域中间件
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Headers", "*");
  ctx.set("Access-Control-Allow-Methods", "*");
  await next();
});

app.use(
  koaBody({
    multipart: true,
    formidable: {
      // 在配置选项option里面，不推荐使用相对路径
      // 在option的相对路径，不是相对于当前文件，而是相对于process.cwd()
      uploadDir: path.join(__dirname, "./upload"),
      // 保持文件后缀名
      keepExtensions: true,
      maxFieldsSize: 10 * 1024 * 1024, // 文件上传大小限制
    },
  })
);
app.use(KoaStatic(path.join(__dirname, "./upload")));
app.use(router.routes()).use(router.allowedMethods());

app.on("error", errHandler);
app.listen(APP_PORT, () => {
  console.log(`server is starting on http://localhost:${APP_PORT}`);
});
